/*
 * @Date: 2022-06-16 11:47:38
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-06-29 15:22:59
 * @FilePath: \taro-music-learn\src\components\AudioCmp\index.tsx
 * @Description: 播放器组件 167876
 */
import React, { memo, useEffect, useRef, useState } from "react";
import { View, Text } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { fetchSongDetailInfo } from "@/store/playSong";
import classNames from "classnames";
import { useDispatch } from "react-redux";
import { useSelector } from "@/store/hooks";
import {
  AtAvatar,
  AtDrawer,
  AtIcon,
  AtList,
  AtListItem,
  AtMessage
} from "taro-ui";
import {
  toggelStatePlayFlag,
  changeCurrentSongBySequence
} from "@/store/playSong";
import MusicInfoItem from "@/components/MusicInfoItem";
import "./index.scss";

const index: React.FC = memo(() => {
  const backgroundAudioManager = Taro.getBackgroundAudioManager();
  const dispatch = useDispatch();
  const [playListShowFlag, setPlayListShowFlag] = useState(false);
  const [playList, setPlayList] = useState<any[]>([]);
  const { currentSongState } = useSelector(state => ({
    currentSongState: state.PlaySong
  }));
  useDidShow(() => {
    backgroundAudioManager.onPause(() => {
      dispatch<any>(toggelStatePlayFlag(false));
    });
    backgroundAudioManager.onPlay(() => {
      dispatch<any>(toggelStatePlayFlag(true));
    });
    backgroundAudioManager.onError(() => {
      Taro.atMessage({
        message: "播放出错了~",
        type: "error",
        duration: 1000
      });
      Taro.stopBackgroundAudio();
      dispatch<any>(toggelStatePlayFlag(false));
    });
  });

  useEffect(() => {
    setCurrentSong();
    dispatch<any>(toggelStatePlayFlag(true));
  }, [currentSongState.currentSong.id]);
  useEffect(() => {
    console.log("当前播放列表", currentSongState.playList);
    setPlayList(currentSongState.playList);
  }, [currentSongState.playList]);
  const toggelPlayFlag = () => {
    if (currentSongState.isPlaying) {
      backgroundAudioManager.pause();
      dispatch<any>(toggelStatePlayFlag(false));
    } else {
      setCurrentSong();
      dispatch<any>(toggelStatePlayFlag(true));
    }
  };
  const go2SongDetail = () => {
    if (currentSongState.currentSong.id) {
      Taro.navigateTo({
        url: "/pages/packageA/songDetail/index"
      });
    } else {
      return;
    }
  };
  const setCurrentSong = () => {
    backgroundAudioManager.coverImgUrl =
      currentSongState.currentSong.al && currentSongState.currentSong.al.picUrl;
    backgroundAudioManager.title =
      currentSongState.currentSong.name && currentSongState.currentSong.name;
    backgroundAudioManager.src = `${currentSongState.currentSong.id &&
      `https://music.163.com/song/media/outer/url?id=${currentSongState.currentSong.id}.mp3`}`;
  };
  const togglePlayListShowFlag = () => {
    setPlayListShowFlag(!playListShowFlag);
  };
  const changeCurrentSong = (id: string) => {
    dispatch<any>(fetchSongDetailInfo(id));
  };
  return (
    <View id="audio-cmp-unique">
      <AtMessage />
      <View className="palyer-container">
        <View className="left-info">
          <View onClick={go2SongDetail}>
            <AtAvatar
              circle
              image={
                currentSongState.currentSong.al &&
                currentSongState.currentSong.al.picUrl
              }
              className={classNames({
                "current-song-pic": true,
                discAnimation: currentSongState.isPlaying,
                pause: !currentSongState.isPlaying
              })}
            ></AtAvatar>
          </View>
          <View className="current-song-info">
            <View className="Audiocmp-song-name">
              {currentSongState.currentSong.name
                ? currentSongState.currentSong.name
                : "暂无歌曲"}
            </View>{" "}
            <View className="Audiocmp-singer">
              {currentSongState.currentSong.ar.length
                ? ` - ${currentSongState.currentSong.ar[0].name}`
                : "未知"}
            </View>
          </View>
        </View>
        <View className="player-btn">
          <AtIcon
            value={currentSongState.isPlaying ? "pause" : "play"}
            className="icon"
            onClick={() => toggelPlayFlag()}
          ></AtIcon>
          <AtIcon value="playlist" onClick={togglePlayListShowFlag}></AtIcon>
        </View>
      </View>
      <AtDrawer
        show={playListShowFlag}
        mask
        right
        onClose={togglePlayListShowFlag}
        style={{ zIndex: 9999 }}
        width="300px"
      >
        {/* <AtList hasBorder={false}> */}
        <View className="drawer-item play-list-item-unique">
          {playList.length
            ? playList.map((item, index) => {
                return (
                  <View
                    key={item.id}
                    onClick={() => {
                      changeCurrentSong(item.id);
                    }}
                  >
                    <MusicInfoItem
                      index={index + 1}
                      songInfo={item}
                      key={item.id}
                      isDelete
                    ></MusicInfoItem>
                  </View>
                );
              })
            : "暂无数据"}
        </View>

        {/* </AtList> */}
      </AtDrawer>
    </View>
  );
});
index.defaultProps = {
  currentSong: {
    id: 0,
    name: "",
    ar: [],
    al: {
      picUrl: "",
      name: ""
    },
    url: "",
    lrcInfo: "",
    dt: 0, // 总时长，ms
    st: 0 // 是否喜欢
  },
  isPlaying: false
};
export default index;
